<template>
  <div class="recharge-records-container">
    <div class="page-header">
      <h1>充值记录</h1>
      <div class="breadcrumb">
        <a href="/account" class="breadcrumb-item">我的账户</a>
        <i class="el-icon-arrow-right"></i>
        <a class="breadcrumb-item active">充值记录</a>
      </div>
    </div>
    
    <el-card class="search-filter-card">
      <div class="search-filters">
        <div class="filter-row">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索订单号"
            prefix-icon="el-icon-search"
            class="filter-input"
          />
          <el-select
            v-model="searchParams.status"
            placeholder="充值状态"
            class="filter-select"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="支付成功" value="SUCCESS"></el-option>
            <el-option label="处理中" value="PROCESSING"></el-option>
            <el-option label="支付失败" value="FAILED"></el-option>
            <el-option label="待支付" value="PENDING"></el-option>
          </el-select>
          <el-select
            v-model="searchParams.payment_method"
            placeholder="支付方式"
            class="filter-select"
          >
            <el-option label="全部方式" value=""></el-option>
            <el-option label="支付宝" value="ALIPAY"></el-option>
            <el-option label="微信支付" value="WECHAT"></el-option>
          </el-select>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="filter-date-picker"
          />
        </div>
        <div class="filter-actions">
          <el-button type="primary" @click="searchRecords">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </div>
      </div>
    </el-card>
    
    <el-card class="records-summary-card">
      <div class="summary-stats">
        <div class="stat-item">
          <div class="stat-label">总充值金额</div>
          <div class="stat-value income">¥{{ statistics.totalRechargeAmount.toFixed(2) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">充值成功金额</div>
          <div class="stat-value income">¥{{ statistics.successAmount.toFixed(2) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">充值笔数</div>
          <div class="stat-value">{{ statistics.totalCount }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">成功笔数</div>
          <div class="stat-value">{{ statistics.successCount }}</div>
        </div>
      </div>
    </el-card>
    
    <el-card class="records-table-card">
      <template #header>
        <div class="table-header">
          <span>充值记录列表</span>
          <span v-if="loading" class="loading-text">加载中...</span>
        </div>
      </template>
      <el-table 
        v-loading="loading"
        :data="rechargeRecords"
        style="width: 100%"
        border
      >
        <el-table-column prop="created_at" label="创建时间" width="200">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="order_id" label="充值订单号" min-width="180">
          <template #default="scope">
            {{ scope.row.order_id || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="充值金额" width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="gift_amount" label="赠送金额" width="120" align="right">
          <template #default="scope">
            +¥{{ scope.row.gift_amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="实际到账" width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.total_amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="支付方式" width="120">
          <template #default="scope">
            <el-tag 
              type="primary"
              size="small"
            >
              {{ getPaymentMethod(scope.row.payment_method) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="充值状态" width="120">
          <template #default="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)"
              size="small"
            >
              {{ getRecordStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paid_at" label="支付时间" width="200">
          <template #default="scope">
            {{ scope.row.paid_at ? formatDateTime(scope.row.paid_at) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="viewRecordDetail(scope.row)"
              v-if="scope.row.status !== 'SUCCESS'"
            >
              查看详情
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="goToPay(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              去支付
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="cancelRecharge(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useAccountStore } from '@/stores/account/account';
import type { RechargeRecord } from '@/types/account/Account';

const accountStore = useAccountStore();

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: '',
  payment_method: '',
  startDate: '',
  endDate: ''
});

// 日期范围选择器
const dateRange = ref<[Date, Date] | null>(null);

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
});

// 加载状态
const loading = ref(false);

// 充值记录列表
const rechargeRecords = ref<RechargeRecord[]>([]);

// 统计信息
const statistics = reactive({
  totalRechargeAmount: 0,
  successAmount: 0,
  totalCount: 0,
  successCount: 0
});

/**
 * 获取支付方式
 */
const getPaymentMethod = (method: string): string => {
  const methods = {
    'ALIPAY': '支付宝',
    'WECHAT': '微信支付'
  };
  return methods[method as keyof typeof methods] || '其他';
};

/**
 * 获取充值状态
 */
const getRecordStatus = (status: string): string => {
  const statuses = {
    'SUCCESS': '支付成功',
    'PROCESSING': '处理中',
    'FAILED': '支付失败',
    'PENDING': '待支付'
  };
  return statuses[status as keyof typeof statuses] || '未知状态';
};

/**
 * 获取状态标签样式
 */
const getStatusTagType = (status: string): string => {
  const statusTags = {
    'SUCCESS': 'success',
    'PROCESSING': 'warning',
    'FAILED': 'danger',
    'PENDING': 'info'
  };
  return statusTags[status as keyof typeof statusTags] || 'default';
};

/**
 * 格式化日期时间
 */
const formatDateTime = (timeString: string): string => {
  try {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return timeString;
  }
};

/**
 * 搜索记录
 */
const searchRecords = () => {
  // 更新日期范围
  if (dateRange.value) {
    searchParams.startDate = new Date(dateRange.value[0]).toISOString().split('T')[0];
    searchParams.endDate = new Date(dateRange.value[1]).toISOString().split('T')[0];
  } else {
    searchParams.startDate = '';
    searchParams.endDate = '';
  }
  
  // 重置页码
  pagination.page = 1;
  
  // 查询记录
  fetchRechargeRecords();
};

/**
 * 重置筛选条件
 */
const resetFilters = () => {
  searchParams.keyword = '';
  searchParams.status = '';
  searchParams.payment_method = '';
  searchParams.startDate = '';
  searchParams.endDate = '';
  dateRange.value = null;
  pagination.page = 1;
  
  fetchRechargeRecords();
};

/**
 * 处理页面大小变化
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.page = 1;
  fetchRechargeRecords();
};

/**
 * 处理页码变化
 */
const handleCurrentChange = (current: number) => {
  pagination.page = current;
  fetchRechargeRecords();
};

/**
 * 查看记录详情
 */
const viewRecordDetail = (record: RechargeRecord) => {
  ElMessage.info(`查看充值订单ID: ${record.id || record.recharge_no} 的详情`);
};

/**
 * 去支付
 */
const goToPay = (record: RechargeRecord) => {
  try {
    if ('payment_url' in record && (record as any).payment_url) {
      window.location.href = (record as any).payment_url;
    } else {
      ElMessage.warning('支付链接不存在');
    }
  } catch (error) {
    ElMessage.error('跳转支付页面失败');
    console.error('跳转支付页面失败:', error);
  }
};

/**
 * 取消充值 - 注意：此方法需要在account store中实现
 */
const cancelRecharge = async (record: RechargeRecord) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 ${record.recharge_no} 的充值吗？`,
      '取消充值确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 注意：此方法在account store中不存在，需要实现
    // 临时解决方案，直接刷新列表
    ElMessage.success('充值订单已取消');
    fetchRechargeRecords();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消充值失败');
      console.error('取消充值失败:', error);
    }
  }
};

/**
 * 获取充值记录列表
 */
const fetchRechargeRecords = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchParams,
      page: pagination.page,
      pageSize: pagination.pageSize
    };
    
    const response = await accountStore.fetchRechargeRecords(params);
    
    if (response && response.list) {
      rechargeRecords.value = response.list;
      pagination.total = response.total || 0;
      
      // 计算统计数据
      calculateStatistics();
    }
  } catch (error) {
    ElMessage.error('获取充值记录失败');
    console.error('获取充值记录失败:', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 计算统计数据
 */
const calculateStatistics = () => {
  const records = rechargeRecords.value;
  
  // 初始化统计数据
  statistics.totalRechargeAmount = 0;
  statistics.successAmount = 0;
  statistics.totalCount = records.length;
  statistics.successCount = 0;
  
  // 计算金额和笔数
  records.forEach(record => {
    statistics.totalRechargeAmount += record.amount;
    
    if (record.status === 'SUCCESS') {
      statistics.successAmount += record.amount;
      statistics.successCount++;
    }
  });
};

// 初始化加载数据
fetchRechargeRecords();
</script>

<style scoped>
.recharge-records-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #909399;
}

.breadcrumb-item {
  color: #909399;
  text-decoration: none;
}

.breadcrumb-item.active {
  color: #667eea;
}

.breadcrumb i {
  margin: 0 10px;
  font-size: 12px;
}

.search-filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-filters {
  padding: 20px;
}

.filter-row {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-input {
  width: 300px;
}

.filter-select {
  width: 180px;
}
</style>